<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2022/3/5
 * Time: 11:27
 */

namespace app\api\controller;
use app\common\controller\Api;
use think\Db;
use think\Request;
use addons\epay\library\QRCode;
use addons\epay\library\Service;
class Programme extends Api
{
    protected $noNeedLogin = ['type','list','detail'];
    protected $noNeedRight = '*';
    protected $model = null;
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\sign_up\Programme;

    }

    /**
     * 分类
     */
    public function type()
    {
        $purpose = Db::name('course_type_purpose')->field('id,title,is_home')->select();
        if(!$purpose )
            $this->error('暂无数据');
        $this->success('',$purpose);
    }

    /**
     * 方案列表
     */
    public function list()
    {
        if (!Request::instance()->isPost())
            $this->error('请求方式不正确');
        $page = input('post.page',1);
        $limit = input('post.limit',10);

        $where = [];
        $order = [];
        if($course_type_id = input('post.course_type_id'))
        {
            $where['ed_programme.course_type_id'] = $course_type_id;
        }
        if($course_type_purpose_id = input('post.course_type_purpose_id'))
        {
            $where['ed_programme.course_type_purpose_id'] = ['like','%'.$course_type_purpose_id.'%'];
        }
        if($people_number = input('post.people_number'))
        {
            $where['ed_programme.people_number'] = $people_number;
        }
        if($days = input('post.days'))
        {
            $where['ed_programme.days'] = $days;
        }

        if($heat = input('post.heat'))
        {
            $order['heat'] = $heat;
        }

        if($satisfaction = input('post.satisfaction'))
        {
            $order['satisfaction'] = $satisfaction;
        }

        if($price = input('post.price'))
        {
            $order['price'] = $price;
        }

        $list = $this->model
            ->with(['type'])
            ->where($where)
            ->order($order)
            ->paginate($limit,false,['page'=>$page]);

        foreach ($list as $row) {
            $purpose = Db::name('course_type_purpose')->where(['id'=>['in',$row['course_type_purpose_id']]])->field('id,title')->select();
            $order_total = Db::name('order')->where(['type'=>3,'programme_id'=>$row['id'],'state'=>1,'status'=>1])->count('id');
            $row['purpose'] = $purpose;
            $row['total'] = intval($order_total);
            $row->visible(['id','title','image','product_detail','satisfaction','people_number','days','total','paid_view','price','purpose','paid_download','createtime']);
            $row->visible(['type']);
            $row->getRelation('type')->visible(['title']);

        }
        if($list)
            $this->success('',$list);
        $this->error('暂无数据');

    }

    /**
     * 点赞/收藏
     */
    public function like()
    {
        if (!Request::instance()->isPost())
            $this->error('请求方式不正确');

        if(!$programme_id = input('post.programme_id'))
        {
            $this->error('缺少参数');
        }

        if(!$type = input('post.type'))
        {
            $this->error('缺少参数');
        }

        if(!$status = input('post.status'))
        {
            $this->error('缺少参数');
        }

        $user_id = $this->auth->id;
        $data = [];
        $data['user_id'] = $user_id;
        $data['programme_id'] = $programme_id;
        $data['createtime'] = time();
        $data['updatetime'] = time();
        $arr=[
            'likes'=>'点赞',
            'collect'=>'收藏'
            ];


        if($status==1)
        {
            Db::startTrans();
            try{
                $res = Db::name($type)->where(['user_id'=>$user_id,'programme_id'=>$programme_id])->find();
                if($res)
                    $this->error('请勿重复'.$arr[$type]);
                Db::name($type)->insert($data);
                db::name('programme')->where('id',$programme_id)->setInc($type);
                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                $this->error($arr[$type].'失败');
                // 回滚事务
                Db::rollback();
            }
            $this->success($arr[$type].'成功');
        }
        else
        {
            Db::startTrans();
            try{
                Db::name($type)->where(['user_id'=>$user_id,'programme_id'=>$programme_id])->delete();
                db::name('programme')->where('id',$programme_id)->setDec($type);
                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                $this->success('取消'.$arr[$type].'失败');
                Db::rollback();
            }
            $this->success('取消'.$arr[$type].'成功');

        }

    }

    /**
     * 方案详情
     */
    public function detail()
    {
        if (!Request::instance()->isGet())
            $this->error('请求方式不正确');
        if(!$id=input('get.id'))
            $this->error('缺少参数');

        $info = $this->model->field('id,title,price,days,people_number,characteristic,people_number,images,free_browsing,product_detail,introduce,route_introduction,schedule,fee_description,reservation_notice,custom_made,precautions,course_type_id,satisfaction')->where('id',$id)->find();

        if(!$info)
            $this->error('缺少参数');
        $name = '';
        switch ($info['people_number'])
        {
            case 1:
                $name = '10人以下';
                break;
            case 2:
                $name = '10~30人';
                break;
            case 3:
                $name = '30~50人';
                break;
            case 4:
                $name = '50~100人';
                break;
            case 5:
                $name = '100人以上';
                break;
            case 6:
                $name = '人数不限';
                break;
        }
        Db::name('programme')->where('id',$id)->setInc('look');
        //定制数
        $info['customize_number'] = Db::name('order')->where(['type'=>3,'programme_id'=>$id,'state'=>1,'status'=>1])->count('id');;
        //评论数
        $info['comment_number'] = 0;
        $info['pdf_image'] = [];
        $info['satisfaction'] = ($info['satisfaction']*100).'%';
        if(intval($info['free_browsing'])==0)
        {
            if($info['images']!='')
            {
                $info['pdf_image'] = explode(',',$info['images']);
            }
        }
        else
        {
            if($info['images']!='')
            {
                $imagesArray = explode(',',$info['images']);
                $end = intval($info['free_browsing']);
                if($end>count($imagesArray))
                {
                    $end = count($imagesArray);
                }
                $info['pdf_image'] = array_slice($imagesArray,0,$end);
            }
        }
        unset($info['images']);
        $info['people_text'] = $name;
        $this->success('',$info);
    }

    /**
     *下载ppt地址
     */
    public function downloadPpt()
    {
        if (!Request::instance()->isPost())
            $this->error('请求方式不正确');
        if(!$id = input('post.id'))
            $this->error('缺少参数');

        $data = [];

       $order = Db::name('order')->where(['user_id'=>$this->auth->id,'programme_id'=>$id,'type'=>2,'state'=>1])->find();

       if($order && $order['status']==1)
       {
           $file = Db::name('programme')->where('id',$id)->value('file');
           if($file)
           {
               $data['state'] = 1;
               $data['code'] = $file;
               $this->success('',$data);
           }
           else
           {
               $this->error('没有文件');
           }
       }
        $order_id = 0;
        if($order && $order['status']==0)
        {
            $order_id = $order['id'];
        }
        else
        {
            $order_id = $this->createOrder();
        }

        $code = $this->wechat($order_id);
        $data['state'] = 2;
        $data['code'] = $code;
        $this->success('',$data);

    }

    public function wechat($order_id)
    {

        $config = Service::getConfig('wechat');

        $type = 'wechat';
        $method = 'scan';
        $orderInfo = Db::name('order')->where('id',$order_id)->find();
        if(!$orderInfo)
            $this->error('无此订单');
        $amount = $orderInfo['price'];
        $this->request->filter('trim');
        $out_trade_no = $orderInfo['order_on'];
        $title = $orderInfo['title'];

        if (!$amount || $amount < 0) {
            $this->error("支付金额必须大于0");
        }

        if (!$type || !in_array($type, ['alipay', 'wechat'])) {
            $this->error("支付类型错误");
        }

        $params = [
            'type'         => $type,
            'orderid' => $out_trade_no,
            'title'        => $title,
            'amount'       => $amount,
            'method'       => $method,
            'openid'       => $config['app_id'],
            //'auth_code'    => $auth_code,
            'notifyurl'    => $config['notify_url'],
            'returnurl'    => '',
        ];

        $response = Service::submitOrder($params);

        $url2 = $this->qrcode($response["code_url"]);
        if($response['return_code']=='SUCCESS')
            return $url2;
        $this->error($response['return_msg']);

    }

    //创建订单
    public function createOrder()
    {
        if(!$id = input('post.id'))
            $this->error('缺少参数');

        if(!$type = input('post.type'))
            $this->error('缺少参数');
        if(!$state = input('post.state'))
            $this->error('缺少参数');
        if(!in_array($type,[1,2,3]))
            $this->error('type参数类型错误');

        if($type==3)
        {
            $info = Db::name('rm_programme')->where('id',$id)->find();
        }
        else
        {
            $info = Db::name('programme')->where('id',$id)->find();
        }
        if(!$info)
            $this->error('无此商品');
        $time = time();
        $out_trade_no = date("YmdHis") .$this->auth->id. mt_rand(100000, 999999);
        $data = [];
        $data['user_id'] = $this->auth->id;
        $data['order_on'] = $out_trade_no;
        $data['type'] = $type;
        $data['state'] = $state;
        if($type==1)
        {
            $data['price'] = $info['paid_view'];
        }
        else if($type==2)
        {
            $data['price'] = $info['paid_download'];
        }
        else
        {
            $data['price'] = $info['price'];
        }
        $data['title'] = $info['title'];
        $data['image'] = $info['image'];
        $data['programme_id'] = $id;
        $data['createtime'] = $time;
        $data['updatetime'] = $time;
        $res = Db::name('order')->insertGetId($data);
        if($res)
            return $res;
        $this->error('程序错误');
    }

    /**
     * 生成二维码
     */
    public function qrcode($url)
    {
        $text = $url;

        //如果有安装二维码插件，则调用插件的生成方法
        if (class_exists("\addons\qrcode\library\Service") && get_addon_info('qrcode')['state']) {

            $qrCode = \addons\qrcode\library\Service::qrcode(['text' => $text]);
            return $qrCode->writeDataUri();

        } else {

            $qr = QRCode::getMinimumQRCode($text);
            return $im = $qr->createImage(8, 5);
        }
    }
    /**
     *查看ppt剩下内容
     */
    public function lookPpt()
    {
        if (!Request::instance()->isGet())
            $this->error('请求方式不正确');
        if(!$id = input('get.id'))
            $this->error('缺少参数');
        if(!$type = input('get.type'))
            $this->error('缺少参数');

        $order = Db::name('order')->where(['user_id'=>$this->auth->id,'programme_id'=>$id,'type'=>1,'status'=>1])->value('id');
        if(!$order)
            //$this->error('你没有购买该方案');

        $info = Db::name('programme')->where('id',$id)->field('images,free_browsing')->find();

        if(!$info)
            $this->error('暂无数据');

        if($info['images']!='')
        {
            $imagesArray = explode(',',$info['images']);
            $info['free_browsing'] = 6;
            $end = intval($info['free_browsing']);
            if($end>count($imagesArray) || $end ==0)
            {
                $end = count($imagesArray);
            }
            if($type==1)
            {
                $info['images'] = array_slice($imagesArray,0,$end);
            }
            else
            {
                $info['images'] = $imagesArray;
            }
        }
        $this->success('',$info);
    }


}